package com.polaris.live.ui.live.activity.end.call

import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.adapter.GainCallEndAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.DateUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.ActivityGainCallEndBinding
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import com.polaris.live.interface_bag.PAGViewListener
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.resp.back_resp.CallStartResp
import com.polaris.live.resp.back_resp.CallVo
import com.polaris.live.resp.bean.CallEndBeansBean
import com.polaris.live.resp.event.CallEndEvent
import com.polaris.live.translation.R.string
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.getBooleanOrString
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.viewmodel.CallEndViewModel
import com.polaris.live.widget.pag.AddFollowView.Companion.LIVE_ADD_FOLLOWE
import jp.wasabeef.glide.transformations.BlurTransformation
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.libpag.PAGView

/**
 * GainCallEndActivity   收益方结算页面
 *
 * @author Created by 半仙 on 2023/9/12/012 11:57
 */
class GainCallEndActivity : BaseVbActivity<CallEndViewModel, ActivityGainCallEndBinding>() {

    private var mCallInfo: CallVo? = null
    private var mCallBean: CallStartResp? = null
    private var mCallMessage: CallSignalingMessage? = null
    private var mCountdown: Boolean? = null

    private var mTime: TimeCount? = null

    private val mAdapter by lazy { GainCallEndAdapter() }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentStatusBar()
            .titleBar(mBinding.icBack)
            .fullScreen(false)
            .transparentNavigationBar()
            .init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)

        mCallInfo = intent.getParcelableExtra(LiveConst.Params.CALL_INFO)
        mCallBean = intent.getParcelableExtra(LiveConst.Params.CALL_BEAN)
        mCallMessage = intent.getParcelableExtra(LiveConst.Params.CALL_MESSAGE)
        mCountdown = intent.getBooleanOrString(LiveConst.Params.CALL_NEED_COUNTDOWN, false)

        initMy()
        initOther()

        val callInfo = mCallInfo
        if (callInfo != null) {
            setBeans(callInfo)

            if (callInfo.follow) {
                mBinding.otherAddFollow.visibility = View.GONE
            }

            mBinding.country.setCountry(mCallMessage?.country)
            if (UserManager.getUser().profile?.secondCountryHidden == AppConst.YES.toLong()) {
                mBinding.myCountry.visibility = View.GONE
            } else {
                mBinding.myCountry.setCountry(UserManager.getUser().profile?.secondCountry)
            }
        }
        initListener()

        if (mCountdown == true) {
            val waitPeriod =
                AppConfigManager.getConfig(CommonConst.Configs.liveEndWaitPeriod)?.toLongOrNull()
                    ?: LiveConst.LIVE_END_WAIT_PERIOD
            mTime = TimeCount(waitPeriod, 1000)
            mTime?.start()
        }

        mBinding.otherAddFollow.apply {
            setPathType(LIVE_ADD_FOLLOWE)
            addListener(object : PAGViewListener {
                override fun onAnimationEnd(p0: PAGView?) {
                    super.onAnimationEnd(p0)
                    mBinding.otherAddFollow.visibility = View.INVISIBLE
                }
            })
            setRepeatCount(1)
        }
    }

    private fun initMy() {
        val user = UserManager.getUser()
        mBinding.callEndMyHead.setImageUrlMiddle(
            user.avatar,
            user.userId
        )
        mBinding.callEndMyName.text = user.nickname
        val isMan =
            user.sex == AppConst.UserSex.MAN || user.sex == AppConst.UserSex.NONE

        user.account?.let {
            if (isMan) {
                mBinding.myLevel.setRichsLevel(it.richs)
            } else {
                mBinding.myLevel.setCharmsLevel(it.charms)
            }
        }
        mBinding.vipView.setVipLevel(user.profile?.vipLevel)
    }

    private fun initOther() {
        val otherUser = LiveUtils.getCallOtherUser(mCallBean, mCallMessage)

        mBinding.callEndOtherHead.setImageUrlMiddle(otherUser?.avatar)
        Glide.with(this).load(otherUser?.avatar?.let { ImageUtils.imgPath(it) })
            .transform(BlurTransformation(15, 3))
            .into(mBinding.callEndBigBackImg)
        mBinding.callEndOtherName.text = otherUser?.nickname

        val isMan =
            otherUser?.sex == AppConst.UserSex.MAN || otherUser?.sex == AppConst.UserSex.NONE
        val richs = otherUser?.richs ?: 0L
        val charm = otherUser?.charms ?: 0L
        if (isMan) {
            mBinding.otherLevel.setRichsLevel(richs)
        } else {
            mBinding.otherLevel.setCharmsLevel(charm)
        }
        mBinding.vipView1.setVipLevel(otherUser?.vipLevel)
    }

    private fun initListener() {
        mBinding.icBack.setOnSingleClickListener {
            finish()
        }

        mBinding.sureButtom.setOnSingleClickListener {
            finish()
        }

        mBinding.otherAddFollow.setOnSingleClickListener {
            mCallInfo?.payUserId?.let { it1 -> mViewModel.addFollower(it1) }
        }

        mViewModel.mAddFollowerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(string.follower_succeed)
                mBinding.otherAddFollow.play()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun setBeans(callInfo: CallVo) {
        val rewardBeans =
            "${StringUtils.getString(string.rewards)} ${StringUtils.getString(string.beans)}:"
        val incomeBeans =
            "${StringUtils.getString(string.income)} ${StringUtils.getString(string.beans)}:"
        val giftsIncome = StringUtils.getString(string.gifts_income)

        val mUserSendGainCoin = callInfo.userSendGainCoin
        val mUserGainCoin = callInfo.userGainCoin
        val mGiftCoin = callInfo.userGiftGainCoin

        val list = mutableListOf<CallEndBeansBean>()
        val time = DateUtils.formatDuration(callInfo.onlineTime * 1000L)
        list.add(CallEndBeansBean(StringUtils.getString(string.Call_duration), time, false))
        if (mUserSendGainCoin != 0L) {
            list.add(
                CallEndBeansBean(rewardBeans, "$mUserSendGainCoin", true)
            )
        }
        if (mUserGainCoin != 0L) {
            list.add(
                CallEndBeansBean(incomeBeans, "$mUserGainCoin", true)
            )
        }
        if (mGiftCoin != 0L) {
            list.add(CallEndBeansBean(giftsIncome, "$mGiftCoin", true))
        }

        mBinding.gainRecycler.apply {
            adapter = mAdapter
            layoutManager = GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false)
        }
        mAdapter.setList(list)
    }

    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            mBinding.sureButtom.text =
                StringUtils.getString(string.ready_next, millisUntilFinished / 1000)
        }

        override fun onFinish() {
            finish()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: CallEndEvent) {
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)

        mTime?.cancel()
        mTime = null
    }
}